/*
 * Copyright (C) 2011 Jake Wharton
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pricy.me;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.atermenji.android.iconictextview.IconicFontDrawable;
import com.atermenji.android.iconictextview.icon.FontAwesomeIcon;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.pricy.me.adapters.CategoryChoiceAdapter;
import com.pricy.me.adapters.NotificationAdapter;
import com.pricy.me.model.CategoryIcon;
import com.pricy.me.model.Notification;
import com.pricy.me.model.User;

public abstract class ActionItems extends SherlockActivity {
	private Handler notifHandler;
	private List<Notification> notifications;
	abstract void actualiser();
    abstract int whereami();
    public static final int STREAM_PRODUCT_ACTIVITY = 0;
    public static final int MYPRODUCTS_ACTIVITY = 1;
    public static final int DISCOVER_ACTIVITY = 2;
    public static final int PRODUCT_ACTIVITY = 3;
    public static final int CATEGORY_CHOICE_ACTIVITY = 4;
    public static final int USER_PROFILE_ACTIVITY = 5;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Used to put dark icons on light action bar
        boolean isLight = false;

        if(whereami() != MYPRODUCTS_ACTIVITY)
        	menu.add(0, 0, 0, ActionItems.this.getString(R.string.me))
            	//.setIcon(isLight ? R.drawable.ic_compose_inverse : R.drawable.ic_monprofile)
            	.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

        menu.add(0, 1, 1,ActionItems.this.getString(R.string.discover))
        	//.setIcon(isLight ? R.drawable.ic_refresh_inverse : R.drawable.ic_explorer)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        
        menu.add(0, 2, 2,ActionItems.this.getString(R.string.search))
        .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.ic_search)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        
        menu.add(0, 3, 3,ActionItems.this.getString(R.string.actualise))
	        .setIcon(isLight ? R.drawable.ic_refresh_inverse : R.drawable.ic_refresh)
	        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        
        menu.add(0, 4, 4,ActionItems.this.getString(R.string.option))
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        
        
        return true;
        
    }
    @Override
    public void setTheme(int resid) {
    	super.setTheme(R.style.Theme_Styled);
    }
    
    @Override
    public void onBackPressed() {
      this.finish();
      overridePendingTransition(0, 0);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if(item.getItemId() == android.R.id.home) {
	    	finish();
	    	overridePendingTransition(0, 0);
            return super.onOptionsItemSelected(item);
        }
        
        
    	switch (item.getOrder()) {
		case 0:
			final Intent myStream = new Intent(getApplicationContext(), MyProductsActivity.class);
			myStream.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
	    	startActivity(myStream);
			break;
		case 1:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(ActionItems.this.getString(R.string.discover));
			CategoryIcon c = new CategoryIcon(0);
			final List<CategoryIcon> data = c.getAll(this);

	        CategoryChoiceAdapter adapter = new CategoryChoiceAdapter(this, data);
			builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int item) {
					final Intent discover = new Intent(getApplicationContext(), DiscoverActivity.class);
					discover.putExtra(ActionItems.this.getString(R.string.category), item);
					discover.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			    	startActivity(discover);
				}

			});
			AlertDialog alert = builder.create();
			alert.show();
			break;
		case 2:

			LayoutInflater li = LayoutInflater.from(ActionItems.this);
			View promptsView = li.inflate(R.layout.search, null);

			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					ActionItems.this);

			// set prompts.xml to alertdialog builder
			alertDialogBuilder.setView(promptsView);

			final EditText search = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
			
			final User user = new User();
			user.loadData(ActionItems.this);

			// set dialog message
			alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton(ActionItems.this.getString(R.string.search),
				  new DialogInterface.OnClickListener() {
				    public void onClick(DialogInterface dialog,int id) {
				    	dialog.dismiss();
				    }
				  })
				.setNegativeButton(ActionItems.this.getString(R.string.cancel),
				  new DialogInterface.OnClickListener() {
				    public void onClick(DialogInterface dialog,int id) {
				    	dialog.cancel();
				    }
				  });

			// create alert dialog
			AlertDialog alertDialog = alertDialogBuilder.create();
			// show it
			alertDialog.show();
			break;
		case 3:

			actualiser();

			break;
		case 4:
			final Intent intent = new Intent(getApplicationContext(), Preferences.class);
	    	startActivity(intent);
			break;

		default:
			break;
		}
    	return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text);
        setContent((TextView)findViewById(R.id.text));
        
      //Inflate the custom view
        View customNav = LayoutInflater.from(this).inflate(R.layout.custom_menu_view, null);
        // Set view title
        final TextView activityTitle = (TextView) customNav.findViewById(R.id.activity_title);
        final ImageView btnMenuBack = (ImageView) customNav.findViewById(R.id.btnmenuback);
        final ImageView btnLogo = (ImageView) customNav.findViewById(R.id.btnlogo);
        switch (whereami()) {
        case STREAM_PRODUCT_ACTIVITY:
			activityTitle.setText(ActionItems.this.getString(R.string.home));
			btnMenuBack.setVisibility(View.GONE);
			break;
		case MYPRODUCTS_ACTIVITY:
			activityTitle.setText(ActionItems.this.getString(R.string.myProfil));
			break;
		case DISCOVER_ACTIVITY:
			activityTitle.setText(ActionItems.this.getString(R.string.discover));
			break;	
		case USER_PROFILE_ACTIVITY:
			activityTitle.setText(ActionItems.this.getString(R.string.userProfil));
			break;
		case CATEGORY_CHOICE_ACTIVITY:
			activityTitle.setText(ActionItems.this.getString(R.string.choiceCategorie));
			break;
		default:
			break;
		}
        if(whereami() != STREAM_PRODUCT_ACTIVITY)
        // Set Button Back
        btnLogo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ActionItems.this.finish();
		        overridePendingTransition(0, 0);
			}
		});
        
        // Set notification
        ImageView notificationIcon = (ImageView) customNav.findViewById(R.id.notification_icon);
        final IconicFontDrawable iconicFontDrawable = new IconicFontDrawable(getApplicationContext());
        iconicFontDrawable.setIcon(FontAwesomeIcon.BELL_ALT);
        iconicFontDrawable.setIconColor(Color.parseColor("#927961"));
        notificationIcon.setBackgroundDrawable(iconicFontDrawable);
        //Attach to the action bar
        getSupportActionBar().setCustomView(customNav);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
     // Init notification by getting data from webservice
        final TextView notification = (TextView) this.findViewById(R.id.notification);
        notification.setVisibility(View.GONE);
        new Thread() {
			
			@Override
			public void run() {
				User user = new User();
				user.loadData(getApplicationContext());
				HttpClient httpclient = new DefaultHttpClient();
				  final String urlnotification=getString(R.string.lien)+"api/notification/count?user=";
					
	            HttpPost httppost = new HttpPost(urlnotification+user.getId());
	                
	                try {
	                	// Execute HTTP Post Request
		                HttpResponse response = httpclient.execute(httppost);
						String reponse = EntityUtils.toString(response.getEntity());
						Message msg = new Message();
						msg.obj = reponse;
						notifHandler.sendMessage(msg);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
        }.start();
        
        notifHandler = new Handler(){
        	@SuppressWarnings("unchecked")
			@Override
        	public void handleMessage(Message msg) {
        		if(msg.obj != "0"){
        			notification.setVisibility(View.VISIBLE);
        			iconicFontDrawable.setIconColor(Color.parseColor("#FFFFFF"));
        			// Convert JSON to Notification list
        			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
        	    	String jsonOutput = (String) msg.obj;
        	    	
        	    	Type listType = new TypeToken<List<Notification>>(){}.getType();
        	    	if(jsonOutput.length() < 2){
        	    		ArrayList<Notification> empty = new ArrayList<Notification>();
        	    		jsonOutput = gson.toJson(empty);
        	    	}
        	    	
					notifications = (List<Notification>) gson.fromJson(jsonOutput, listType);
					
					if(notifications.size() == 0) {
						notification.setVisibility(View.GONE);
						iconicFontDrawable.setIconColor(Color.parseColor("#927961"));
					}
					else notification.setText(""+notifications.size());
        		}
        	}
        };
        
        // Open notifications on click
        // if(notification.getVisibility() == View.VISIBLE){
	        final RelativeLayout notificationBtn = (RelativeLayout) this.findViewById(R.id.notification_btn);
	        notificationBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(notification.getVisibility() != View.GONE){
						final List<Notification> mData = notifications;
						
				        final Dialog dialog = new Dialog(ActionItems.this);
				        dialog.setContentView(R.layout.notification_list_view);
				        ListView mListView = (ListView) dialog.findViewById(R.id.notification_lv_list);
				        
				        NotificationAdapter mAdapter = new NotificationAdapter(ActionItems.this, mData);
				        mListView.setAdapter(mAdapter);
				        dialog.setTitle(ActionItems.this.getString(R.string.notification));
				        dialog.show();
				        
				        mListView.setOnItemClickListener(new OnItemClickListener() {
		
							@Override
							public void onItemClick(AdapterView<?> arg0, View arg1,
									int position, long arg3) {
								
								final Intent discover = new Intent(getApplicationContext(), ProductActivity.class);
								Log.e("ID", ""+mData.get(position).getObjectId());
								Log.e("ID", ""+mData.get(position).getObject());
								Log.e("ID", ""+mData.get(position).getUsername());
								Log.e("ID", ""+mData.get(position).getUserpicture());
							discover.putExtra(ActionItems.this.getString(R.string.product), notifications.get(position).getObjectId());
								discover.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
						    	startActivity(discover);
								
							}
						
				        });
					}
				}
			});
        }
    //}

    protected void setContent(TextView view) {
        view.setText(R.string.action_items_content);
    }
}
